import dayjs from "dayjs"
import relativeTime from "dayjs/plugin/relativeTime"
import 'dayjs/locale/zh-cn'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')
/**
 * 判断是否是外部资源
 * @param url 
 * @returns 
 */
export const isExternal = (url: string) => {
    return /^https?:\/\/.+/.test(url)
}

/**
 * 判断 node元素是否是target的子元素或者相同元素
 * @param target 目标元素
 * @param node 对比元素
 * @returns 对比结果
 */
export const isSameNode = (target: Element, node: Element | null): boolean => {
    if (!target || !node) return false
    if (target === node) return true
    return isSameNode(target, node.parentNode as Element)
}

/**
 * 获取文本长度
 * @param target 
 * @returns 
 */
export const getElementTextLength = (target: Element | null,) => {
    if (!target) return 0
    const childNodes = Array.from(target.childNodes)
    if (childNodes.length > 0) {
        return childNodes.reduce((acc, one) => {
            acc += getElementTextLength(one as any)
            return acc
        }, 0)
    }
    return target.textContent!.length
}

export const getRelativeTime = (target: dayjs.ConfigType) => {
    return dayjs(target).fromNow()
}